import { inject, onBeforeMount, ref, watch } from "vue";
import { i18n } from "@/i18n";
import { jsonSimpleClone, removeHtmlTag } from "@/views/formgen/utils";
import { getSettingRequest } from "@/api/project/setting";
import { ElMessageBox } from "element-plus";
import { updateFormDataDeletedRequest, updateFormDataRequest } from "@/api/project/data";
import { MessageBoxUtil, MessageUtil } from "@/utils/messageUtil";
import { storeToRefs } from "pinia";
import { useFormInfo } from "@/stores/formInfo";
import { cloneDeep } from "lodash-es";

export function useDataViewOrUpdate(props: any, emit: any) {
  const activeName = ref("info");
  const isEditMode = ref(false);
  const formParseKey = ref(new Date().getTime());
  const currentFormModel = ref(null);

  const formConf = ref({
    formRef: "generateForm",
    fields: [],
    formKey: "",
    disabled: true,
    span: 24,
    size: "default",
    labelPosition: "top",
    labelWidth: 100,
    formRules: "rules",
    gutter: 15,
    formBtns: false,
    resetBtn: false,
    theme: {
      backgroundImg: "",
      showFormTitle: true,
      showFormDescribe: true,
      showFormNumber: false,
      btnsColor: null
    }
  });

  const dialogVisible = ref(false);
  const dialogTitle = ref(i18n.global.t("form.viewOrUpdate.view"));
  const fullscreen = ref(false);
  const openReply = ref(false);
  const isPrint = ref(false);
  const remarkEditDisable = ref(false);
  const remarkButton = ref("");

  const printForm = ref({
    id: "printForm",
    popTitle: "",
    preview: false,
    extraHead:
      '<meta http-equiv="Content-Language" content="zh-cn"/>,<style>  #printForm { width: 100%;  }  .not-print {display: none!important } .print{ display: block!important}<style>',
    previewBeforeOpenCallback(vue) {
      //console.log("正在加载预览窗口");
    },
    previewOpenCallback(vue) {
      //console.log("已经加载完预览窗口");
    },
    beforeOpenCallback(vue) {
      //console.log("打开之前");
      // console.log(vue); // 这里检查是否包含所有内容
    },
    openCallback(vue) {
      //console.log("执行了打印");
    },
    closeCallback(vue) {
      //console.log("关闭了打印工具");
    }
  });

  watch(
    () => props.fields,
    val => {
      formConf.value.fields = val
        .filter(item => {
          return item.scheme;
        })
        .map(item => {
          if (item.scheme) {
            item.scheme.viewMode = true;
            // 去除标签中富文本
            item.scheme.config.label = removeHtmlTag(item.scheme.config.label);
          }
          return item.scheme;
        });
    },
    { deep: true, immediate: true }
  );

  onBeforeMount(() => {
    queryUserProjectSetting();
  });

  const checkBtnPermsFunc = inject("checkBtnPerms");

  const checkBtnPerms = btn => {
    return checkBtnPermsFunc(btn);
  };

  // 维度
  const dimensionConfig = inject("dimensionConfig");

  // 全部数据列表1
  const dataList = ref([]);
  const currentDataIndex = ref(1);

  const handlePageChange = num => {
    if (currentDataIndex.value === 1 && num === -1) {
      return;
    }
    if (currentDataIndex.value === dataList.value.length && num === 1) {
      return;
    }
    currentDataIndex.value = currentDataIndex.value + num;
    currentFormModel.value = jsonSimpleClone(dataList.value[currentDataIndex.value - 1]);
    isEditMode.value = false;
    initDialog();
  };

  const showDialog = (formModel, tableList) => {
    currentFormModel.value = jsonSimpleClone(formModel);
    initDialog();
    dataList.value = tableList;
    currentDataIndex.value = tableList.findIndex(item => item.id === formModel?.id) + 1;
  };

  const initDialog = () => {
    formConf.value.disabled = true;
    dialogTitle.value = i18n.global.t("form.viewOrUpdate.view");
    formParseKey.value = new Date().getTime();
    isEditMode.value = false;
    dialogVisible.value = true;
    remarkEditDisable.value = true;
    remarkButton.value = i18n.global.t("form.viewOrUpdate.edit");
    activeName.value = "info";
  };

  const handleCancel = () => {
    if (isEditMode.value) {
      isEditMode.value = false;
      formConf.value.disabled = true;
      return;
    }
    dialogVisible.value = false;
    emit("reload");
    // 返回上一页
    router.back();
  };

  const handleEditMode = () => {
    isEditMode.value = true;
    dialogTitle.value = i18n.global.t("form.viewOrUpdate.edit");
    formConf.value.disabled = false;
  };

  const handleFullScreen = () => {
    fullscreen.value = !fullscreen.value;
  };

  const queryUserProjectSetting = () => {
    getSettingRequest(props.formKey).then(res => {
      if (res.data) {
        openReply.value = res.data.openReply;
      }
    });
  };

  const dataShareRef = ref(null);

  const handleShowDataShare = () => {
    dataShareRef.value.show(currentFormModel.value?.id, currentFormModel.value?.dataId, props.fields);
  };

  const handleDelete = () => {
    ElMessageBox.alert(i18n.global.t("form.viewOrUpdate.irreversibleDeletion"), i18n.global.t("formI18n.all.waring"), {
      confirmButtonText: i18n.global.t("formI18n.all.confirm"),
      callback: action => {
        if (action === "confirm")
          updateFormDataDeletedRequest(props.formKey, [currentFormModel.value?.id], true).then(res => {
            MessageUtil.success(i18n.global.t("formI18n.all.success"));
            dialogVisible.value = false;
            emit("reload");
          });
      }
    });
  };

  const generateFormRef = ref(null);

  const updateFromRequest = () => {
    let formModel: Record<string, any> = cloneDeep(generateFormRef.value?.formModel);
    let tempFormModel: Record<string, any> = {};
    for (let key in formModel) {
      let bool = /.*\d+.*/g.test(key);
      if (bool) {
        tempFormModel[key] = formModel[key];
      }
      //如果值是undefined，就改成null
      if (formModel[key] === undefined) {
        tempFormModel[key] = null;
      }
    }
    console.log(formModel);
    console.log(tempFormModel);
    updateFormDataRequest({
      id: currentFormModel.value?.id,
      completeTime: null,
      formKey: props.formKey,
      submitOs: "",
      submitBrowser: "",
      submitUa: null,
      wxUserInfo: null,
      wxOpenId: "",
      originalData: tempFormModel
    }).then(() => {
      MessageUtil.success(i18n.global.t("formI18n.all.success"));
      dialogVisible.value = false;
      setTimeout(() => {
        emit("reload");
      }, 1000);
    });
  };

  const handleUpdate = () => {
    generateFormRef.value!.validateForm().then(valid => {
      if (valid) {
        updateFromRequest();
      } else {
        MessageBoxUtil.confirm(
          i18n.global.t("form.viewOrUpdate.forceSaveText"),
          () => {
            updateFromRequest();
          },
          i18n.global.t("form.viewOrUpdate.confirm")
        );
      }
    });
  };

  const { formType } = storeToRefs(useFormInfo());

  return {
    handleShowDataShare,
    handleDelete,
    updateFromRequest,
    handleUpdate,
    formType,
    currentFormModel,
    dialogVisible,
    dialogTitle,
    activeName,
    isEditMode,
    formParseKey,
    formConf,
    isPrint,
    fullscreen,
    openReply,
    remarkEditDisable,
    printForm,
    checkBtnPerms,
    dimensionConfig,
    dataList,
    handlePageChange,
    currentDataIndex,
    showDialog,
    initDialog,
    handleCancel,
    handleEditMode,
    handleFullScreen,
    dataShareRef,
    generateFormRef
  };
}

export const viewOrUpdateProps = {
  fields: {
    type: Array,
    default: () => []
  },
  fixedFields: {
    type: Array,
    default: () => []
  },
  formKey: {
    type: String,
    default: ""
  },
  canUpdate: {
    type: Boolean,
    default: false
  }
};

export const viewOrUpdateEmits = ["reload", "openReply"];
